import java.io.File;
import java.io.FileNotFoundException;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;




public class BerkeleyDBManager {

	private Database dbHandle = null;
	private Environment envHandle = null;
	//private ObjectSerializer serializer = null;
	
	public static String ENV_HOME = "DB";
	public static String DB_NAME = "TestDB";
	
	public BerkeleyDBManager(String id) throws FileNotFoundException, DatabaseException {
		//serializer = new ObjectSerializer();
		//ENV_HOME = ENV_HOME + id;
		open();
	}
	
	@Override
	protected void finalize() throws Throwable {
		// TODO Auto-generated method stub
		close();
		super.finalize();		
	}
	
	public void open() throws FileNotFoundException, DatabaseException
	{
		EnvironmentConfig environmentConfig = new EnvironmentConfig();
		environmentConfig.setAllowCreate(true);
		environmentConfig.setLocking(true);
		environmentConfig.setTransactional(true);
		//environmentConfig.setInitializeCache(true);		
		//environmentConfig.setThreaded(true);
		//environmentConfig.setMode(DbConstants.DB_THREAD);
		//environmentConfig.set
		//environmentConfig.setMaxMutexes(600);
		// perform other environment configurations
		File file = new File(ENV_HOME);
		envHandle = new Environment(file, environmentConfig);
		DatabaseConfig databaseConfig = new DatabaseConfig();
		databaseConfig.setTransactional(true);
		//databaseConfig.setTransactional(true);
		databaseConfig.setAllowCreate(true);	
		//databaseConfig.setType(0);
		//databaseConfig.setMode(DbConstants.DB_THREAD);
		// perform other database configurations
		dbHandle = envHandle.openDatabase(null, DB_NAME, databaseConfig);
	}
	
	public void close() throws DatabaseException
	{
		dbHandle.sync();
		dbHandle.close();
		envHandle.close();		
	}
	
	public synchronized void put(DataObject key,DataObject val)
	{
	    try {
	        DatabaseEntry dbkey = new DatabaseEntry(key.getVal());
	        DatabaseEntry dbval = new DatabaseEntry(val.getVal());
	        dbHandle.put(null, dbkey, dbval);
	        //dbHandle.sync();
	    } catch (Exception e) {
	        System.out.println("Database error");
	        e.printStackTrace();
	    }
	}
	
	public DataObject get(DataObject key)
	{
		DatabaseEntry dbval = null,dbkey = null;
		try {
	        dbkey = new DatabaseEntry(key.getVal());
	        dbval = new DatabaseEntry();
	        dbHandle.get(null, dbkey, dbval, null);
	    } catch (Exception e) {
	        System.out.println("Database error");
	        e.printStackTrace();
	        return null;
	    }
	    DataObject value = new DataObject(dbval.getData());
	    return value;		
	}
	
	
	
}
